package com.syedu.day17;

import com.google.common.collect.Lists;

import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.function.Supplier;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * description：JDK8.0新特性: Stream流式API -- 惰性计算
 *
 * @author Administrator
 * @date 2022/4/8 14:06
 */
public class StreamAPI {
    public static void main(String[] args) {
        /**
         * 创建Stream对象
         */
        //1.一般在测试中使用(不推荐)
        Stream<Integer> stream = Stream.of(10, 20, 30, 40, 50);
        stream.forEach(System.out::println);

        //2.基于数组或集合(常用)
        Stream<String> stream1 = Arrays.stream(new String[]{"AA", "BB", "CC", "DD"});
        Stream<Integer> stream2 = Lists.newArrayList(10, 20, 30, 40, 50).stream();

        //3.基于Supplier
        Stream<Integer> stream3 = Stream.generate(new Supplier<>() {
            private int num = 0;

            @Override
            public Integer get() {
                return num++;
            }
        });
        stream3.limit(100).forEach(System.out::println);

        //4.其他方法,某些类中的方法可以得到Stream
        try {
            //注意:如果得到集合,则相当于已经把所有数据加载到内存中了,但是Stream的方式相当于先订立契约,没有真正的加载数据,所以内存开销极少,效率较高
            //List<String> stringList = Files.readAllLines(Path.of("D:\\BAM练习.txt"));
            Stream<String> lines = Files.lines(Path.of("D:\\BAM练习.txt"));//惰性
        } catch (IOException e) {
            e.printStackTrace();
        }

        //补充: Stream泛型不支持基本类型,所以Java额外提供了几个类来支持基本类型的Stream操作,IntStream,LongStream,DoubleStream...
        IntStream intStream = Arrays.stream(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9});

        /**
         * 编写一个能输出斐波拉契数列（Fibonacci）的LongStream
         */
        Stream.generate(new Supplier<BigInteger>() {
            BigInteger n1 = BigInteger.ZERO, n2 = BigInteger.ZERO, n3 = BigInteger.ONE;
            @Override
            public BigInteger get() {
                n1 = n2;
                n2 = n3;
                n3 = n1.add(n2);
                return n2;
            }
        }).limit(10).forEach(System.out::println);

        /**
         * 使用map()把一组String转换为LocalDate并打印
         */
        /*Lists.newArrayList("2022-12-12","2022-04-08","2022-08-20")
                .stream().map(str-> LocalDate.parse(str)).forEach(System.out::println);*/

        Lists.newArrayList("2022-12-12","2022-04-08","2022-08-20")
                .stream().map(LocalDate::parse).forEach(System.out::println);
    }
}